<!-- pages/login/login.vue -->
<template>
    <view class="container">
        <!-- 登录表单 -->
        <template v-if="isLogin">
            <uni-forms ref="loginForm" :modelValue="loginData">
                <uni-forms-item label="账号" name="account">
                    <uni-easyinput v-model="loginData.account" placeholder="请输入账号" />
                </uni-forms-item>
                <uni-forms-item label="密码" name="password">
                    <uni-easyinput type="password" v-model="loginData.password" placeholder="请输入密码" />
                </uni-forms-item>
            </uni-forms>

            <button type="primary" @click="handleLogin">登录</button>
            <view class="link-text" @click="switchForm('register')">没有账号？立即注册</view>
        </template>

        <!-- 注册表单 -->
        <template v-else>
            <uni-forms ref="regForm" :modelValue="regData">
                <uni-forms-item label="手机号" name="phone">
                    <uni-easyinput v-model="regData.phone" maxlength="11" placeholder="请输入手机号" />
                </uni-forms-item>

                <uni-forms-item label="验证码" name="code">
                    <view class="code-input">
                        <uni-easyinput v-model="regData.code" placeholder="请输入验证码" />
                        <button class="send-btn" :disabled="isSending" @click="sendVerifyCode">
                            {{ codeBtnText }}
                        </button>
                    </view>
                </uni-forms-item>

                <uni-forms-item label="密码" name="password">
                    <uni-easyinput type="password" v-model="regData.password" placeholder="请设置登录密码（6-20位）" />
                </uni-forms-item>
            </uni-forms>

            <button type="primary" @click="handleRegister">注册</button>
            <view class="link-text" @click="switchForm('login')">已有账号？去登录</view>
        </template>
    </view>
</template>

<script>
    import {
        checkLogin,
        getUserByAccount,
        login,
        registe
    } from '../../apis/login'
    import {
        setToken
    } from '../../tools/cookieMgr'
    export default {
        data() {
            return {
                isLogin: true,
                isSending: false,
                codeBtnText: '获取验证码',
                countdown: 60,

                // 登录表单数据
                loginData: {
                    account: '',
                    password: ''
                },

                // 注册表单数据
                regData: {
                    phone: '',
                    code: '',
                    password: ''
                },

                // 验证规则
                rules: {
                    account: {
                        rules: [{
                            required: true,
                            errorMessage: '请输入账号'
                        }]
                    },
                    password: {
                        rules: [{
                                required: true,
                                errorMessage: '请输入密码'
                            },
                            {
                                minLength: 6,
                                maxLength: 20,
                                errorMessage: '密码长度6-20位'
                            }
                        ]
                    },
                    phone: {
                        rules: [{
                                required: true,
                                errorMessage: '请输入手机号'
                            },
                            {
                                pattern: /^1[3-9]\d{9}$/,
                                errorMessage: '手机号格式不正确'
                            }
                        ]
                    },
                    code: {
                        rules: [{
                            length: 6,
                            errorMessage: '验证码为6位数字'
                        }]
                    }
                }
            }
        },
        methods: {
            // 切换登录/注册表单
            switchForm(type) {
                this.isLogin = type === 'login'
            },

            // 发送验证码
            async sendVerifyCode() {
                try {
                    await this.$refs.regForm.validateField('phone')

                    // 调用发送验证码接口（这里需要对接实际短信服务）
                    uni.showLoading({
                        title: '发送中...'
                    })
                    setTimeout(() => {
                        uni.hideLoading()
                        this.startCountdown()
                        uni.showToast({
                            title: '验证码已发送',
                            icon: 'success'
                        })
                    }, 1000)

                } catch (e) {
                    return
                }
            },

            // 验证码倒计时
            startCountdown() {
                this.isSending = true
                const timer = setInterval(() => {
                    this.countdown--
                    this.codeBtnText = `${this.countdown}s后重新获取`
                    if (this.countdown <= 0) {
                        clearInterval(timer)
                        this.isSending = false
                        this.codeBtnText = '获取验证码'
                        this.countdown = 60
                    }
                }, 1000)
            },

            // 处理登录
            async handleLogin() {
                try {
                    await this.$refs.loginForm.validate()

                    const res = await login(this.loginData);
                    if (res.code >= 0) {
                        uni.showToast({
                            title: res.message || '登录成功',
                            icon: "success"
                        })
                        setToken(res.data.token)
                        uni.reLaunch({
                            url: "/pages/home/home"
                        })
                    } else {
                        uni.showToast({
                            title: res.message || '账号或密码错误',
                            icon: "error"
                        })
                    }
                } catch (e) {
                    console.log('验证失败:', e)
                }
            },

            // 处理注册
            async handleRegister() {
                try {
                    await this.$refs.regForm.validate()
                    const res = await registe(this.regData)
                    if (res.code >= 0) {
                        uni.showToast({
                            title: '注册成功',
                            icon: "success"
                        })
                        this.loginData.account = this.regData.phone // 自动填充手机号到登录账号
                        this.switchForm('login')
                    } else {
                        uni.showToast({
                            title: "注册失败",
                            icon: "fail"
                        })
                    }

                } catch (e) {
                    console.log('验证失败:', e)
                }
            }
        },
        async onShow() {
            try{
                const res = await checkLogin();
                const res2 = await getUserByAccount();
                if (res.code >= 0 && res2.code >= 0) {
                    var userInfo = res.data;
                    userInfo.user = res2.data;
                    setUserInfo(userInfo)
                    uni.reLaunch({
                        url: "/pages/home/home"
                    })
                }
            }catch{
                
            }
        },
        onReady() {
            // 设置表单校验规则
            var rules1 = {
                ...this.rules
            }
            delete rules1.account
            this.$refs.loginForm.setRules(rules1)
            this.$refs.regForm.setRules(this.rules)
        }
    }
</script>

<style scoped>
    .container {
        padding: 30rpx;
    }

    .code-input {
        display: flex;
        align-items: center;
        gap: 20rpx;
    }

    .send-btn {
        width: 240rpx;
        flex-shrink: 0;
    }

    button {
        margin-top: 40rpx;
    }

    .link-text {
        color: #007AFF;
        text-align: center;
        margin-top: 30rpx;
        font-size: 28rpx;
    }
</style>